package com.biao.test_annotation.refect_test;

import com.biao.test_annotation.InitDemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * 属性赋值测速
 */
public class AssignmentTest {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {

        Class<?> pathClass = Class.forName("com.biao.test_annotation.InitDemo");

        /*
        初始化对象
         */
        // newInstance() 方法默认调用无参构造
        InitDemo instance = (InitDemo) pathClass.newInstance();
        System.out.println(instance);
        // 调用有参构造
        Constructor<?> declaredConstructor = pathClass.getDeclaredConstructor(String.class, Integer.class);
        InitDemo aBiu = (InitDemo) declaredConstructor.newInstance("aBiu", 18);
        System.out.println(aBiu);

        // getFields() 只能获取所有的公有属性,也就是public修饰的
        System.out.println("公有属性有:----------------");
        Field[] fields = pathClass.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }

        // getDeclaredFields() 获取所有属性,公有属性和私有属性都获取
        System.out.println("所有属性:----------------");
        Field[] declaredFields = pathClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }

        // 给公有属性赋值
        InitDemo obj = (InitDemo) pathClass.newInstance();
        Field publicParam = pathClass.getDeclaredField("publicParam");
        publicParam.set(obj, "aaaaaaaaaaaa");
        System.out.println(obj.getPublicParam());
        // 给私有属性赋值
        Field name = pathClass.getDeclaredField("name");
        Field age = pathClass.getDeclaredField("age");
        name.setAccessible(true);
        age.setAccessible(true);
        name.set(obj, "abiu...");
        age.set(obj, 18);
        System.out.println(obj);
    }
}
